#include "FloatTextureEncoding.h"

namespace FinalRendering
{
	namespace Engine
	{
		int ChooseScale(float len)
		{
			for (int i=0; i<255; i++)
			{
				float fi = i/25.5f;
				if (fi > len)
					return i;
			}
			return 255;
		}

		void EncodeData(float * dataIn, Array<unsigned int, true> & dataOut, int width, int height)
		{
			dataOut.SetCapacity(width * height);
			dataOut.Clear();
			for (int i=0; i<width * height; i++)
			{
				float fr,fg,fb;
				fr = dataIn[i*3];
				fg = dataIn[i*3+1];
				fb = dataIn[i*3+2];
				float maxlen = max(fr,max(fg,fb));
				Byte e = ChooseScale(maxlen);
				Byte r,g,b;
				float flen = e/25.5f;
				if (fr<0.0f) fr = 0.0f;
				if (fg<0.0f) fg = 0.0f;
				if (fb<0.0f) fb = 0.0f;
				r = Round(fr / flen * 255.0f);
				g = Round(fg / flen * 255.0f);
				b = Round(fb / flen * 255.0f);
				int pixel = (r)+(g<<8)+(b<<16)+(e<<24);
				dataOut.Add(pixel);
			}
		}

		void DecodeData(unsigned int * dataIn, Array<float, true> & dataOut, int width, int height)
		{
			const float factor = 1.0f/255.0f/255.0f*10.0f;
			dataOut.SetCapacity(width * height * 3);
			dataOut.Clear();
			for (int i=0; i<width * height; i++)
			{
				Byte r,g,b,e;
				r = dataIn[i];
				g = dataIn[i]>>8;
				b = dataIn[i]>>16;
				e = dataIn[i]>>24;
				dataOut.Add(r*e*factor);
				dataOut.Add(g*e*factor);
				dataOut.Add(b*e*factor);
			}
		}
	}
}